<template>
  <view class="login-page">
    <view class="header-image-container">
      <image
        src="https://sail-imgs.oss-cn-beijing.aliyuncs.com/fire-uni/Building.jpg"
        mode="aspectFill"
        class="header-image"
      ></image>
      <view class="overlay"></view>
    </view>

    <view class="form-wrapper">
      <view class="title">欢迎登录<view class="subtitle">使用完整功能</view></view>
      
     
      <view class="input-container">
        <image
          src="https://sail-imgs.oss-cn-beijing.aliyuncs.com/fire-uni/user.png"
          mode="aspectFit"
          class="input-icon"
        ></image>
        <input
          class="input-field"
          placeholder="请输入账号"
          v-model="loginForm.wx_user"
          placeholder-class="placeholder"
          style="margin-left: 12px"
        />
      </view>
      <view class="input-container">
        <image
          src="https://sail-imgs.oss-cn-beijing.aliyuncs.com/fire-uni/password.png"
          mode="aspectFit"
          class="input-icon"
        ></image>
        <input
          :password="!showPassword"
          class="input-field"
          placeholder="请输入密码"
          v-model="loginForm.wx_pawd"
          placeholder-class="placeholder"
          style="margin-left: 12px"
        />
        <uni-icons
          :type="showPassword ? 'eye-filled' : 'eye-slash-filled'"
          size="24"
          color="#94a3b8"
          @tap="togglePasswordVisibility"
        ></uni-icons>
      </view>
      <view class="extra-links">
        
        <text
          class="link"
          ></text
        >
        <text
          class="link"
          @tap="sheep.$helper.toast('联系企业成员修改密码')"
          >忘记密码</text
        >
      </view>
      <button class="login-button" @tap="handleLogin">
        <text class="login-button-text">登 录</text>
      </button>

      <!-- 游客按钮 -->
      <button class="guest-button" @tap="guestLogin">
        <text class="guest-button-text">游客访问</text>
      </button>

     

      <!-- 滑块验证组件 -->
    </view>
    <view v-if="showVerify" class="verify-container">
      <view class="mask-layer" @tap.stop="cancelVerify"></view>
      <view class="verify-content">
        <s-slider-captcha
          :width="300"
          :height="145"
          :bgImage="'https://sail-imgs.oss-cn-beijing.aliyuncs.com/fire-uni/pingtu-background.png'"
          :sliderImage="'https://sail-imgs.oss-cn-beijing.aliyuncs.com/fire-uni/pingtu.png'"
          :sliderX="150"
          :sliderY="50"
          :onSuccess="onVerifySuccess"
          :onFail="onVerifyFail"
          ref="sliderCaptchaRef"
        >
        </s-slider-captcha>
      </view>
    </view>
    <view class="footer">
      <text class="copyright">© 2025 蒙ICP备2024012135号-2</text>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, nextTick } from "vue";
import sheep from "@/sheep";
import { onLoad, onShow } from "@dcloudio/uni-app";
// 导入滑块验证组件
import sSliderCaptcha from "@/sheep/components/s-slider-captcha/s-slider-captcha.vue";
// 导入字体样式
import '@/sheep/scss/font/font.css';

// 初始化用户登录状态
sheep.$store("user").isLogin = false;
const isLogin = ref(true); // Changed to true for development visibility

const showPassword = ref(false);
const showVerify = ref(false);
const sliderCaptchaRef = ref(null);

// 登录表单
const loginForm = reactive({
  wx_user: "",
  wx_pawd: "",
  open_id: "",
});

// 游客登录
const guestLogin = () => {
  sheep.$helper.toast('以游客身份访问');
  sheep.$router.go("/pages/book/index", {}, { reLaunch: true });
};

// 从持久化存储中获取数据
onShow(() => {
  console.log('登录页面加载，从持久化存储获取数据');
  sheep.$helper.toast("请先登录");

  // 获取重定向路径
  const redirect = sheep.$helper.pageTransfer.getData("redirect");
  if (redirect) {
    loginForm.redirect = redirect;
    console.log('从持久化存储获取重定向路径:', loginForm.redirect);
  }

  // 获取open_id
  const open_id = sheep.$helper.pageTransfer.getData("open_id");
  if (open_id) {
    loginForm.open_id = open_id;
    console.log('从持久化存储获取open_id:', loginForm.open_id);
  }
});

onLoad(async (options) => {
  // To prevent auto-login during development, this section is commented out.
  // Uncomment for production.
  // 微信登录
  uni.login({
    provider: "weixin",
    success: (res) => {
      const params = {
        code: res.code,
      };

      // 设置超时时间
      const timeout = setTimeout(() => {
        uni.hideLoading();
        sheep.$helper.toast("请求超时，请重试");
      }, 10000); // 10秒超时

      // 调用登录接口
      sheep.$api.login
        .auth(params)
        .then((authRes) => {
          clearTimeout(timeout); // 清除超时计时器
          if (authRes.code == 200) {
            sheep.$store("user").isLogin = true;
            sheep.$store("user").userInfo = authRes.userInfo;
            console.log("用户信息:", authRes);
            if (authRes.status == 1) {
              // 根据用户类型跳转到不同页面
              switch (authRes.userInfo.wx_type) {
                case "1":
                  sheep.$store("app").template.basic.tabbar.list =
                    sheep.$store("app").template.basic.tabbar.qylist;
                  sheep.$router.go("/pages/qy/index", {}, { reLaunch: true });
                  break;
                case "2":
                  sheep.$store("app").template.basic.tabbar.list =
                    sheep.$store("app").template.basic.tabbar.xflist;
                  sheep.$router.go("/pages/xf/index", {}, { reLaunch: true });
                  break;
                case "3":
                  sheep.$store("app").template.basic.tabbar.list =
                    sheep.$store("app").template.basic.tabbar.otherlist;
                  sheep.$router.go("/pages/other/index", {}, { reLaunch: true });
                  break;
                default:
                  sheep.$store("app").template.basic.tabbar.list =
                    sheep.$store("app").template.basic.tabbar.qylist;
                  sheep.$router.go("/pages/qy/index", {}, { reLaunch: true });
                  break;
              }
            } else {
              isLogin.value = true;
              // debug-登录
              loginForm.open_id = authRes.open_id;
              //loginForm.open_id = "aaaa";
            }
          } else {
            sheep.$helper.toast(authRes.message || "授权失败，请重试");
          }
        })
        .finally(() => {
          uni.hideLoading();
        });
    },
    fail: (err) => {
      console.error("微信登录失败:", err);
      isLogin.value = true;
      // 这里有一个错误，应该在失败时不使用authRes变量
      // loginForm.open_id = authRes.open_id;
      uni.hideLoading();
    },
  });
});

// 处理登录
const handleLogin = () => {
  console.log('点击登录按钮');
  if (!loginForm.wx_user || !loginForm.wx_pawd) {
    uni.showToast({
      title: "请输入账号和密码",
      icon: "none",
    });
    return;
  }

  // 先设置显示滑块验证
  showVerify.value = true;

  // 使用nextTick确保组件已渲染
  nextTick(() => {
    // 再使用setTimeout给组件足够的时间初始化
    setTimeout(() => {
      console.log('尝试显示滑块验证', sliderCaptchaRef.value);
      if (sliderCaptchaRef.value) {
        sliderCaptchaRef.value.showVerify();
      } else {
        console.error('滑块验证组件引用不存在');
        // 如果组件引用不存在，尝试重新设置显示状态
        showVerify.value = false;
        setTimeout(() => {
          showVerify.value = true;
          // 再次尝试获取组件引用
          setTimeout(() => {
            if (sliderCaptchaRef.value) {
              sliderCaptchaRef.value.showVerify();
            } else {
              sheep.$helper.toast('验证组件加载失败，请重试');
            }
          }, 300);
        }, 100);
      }
    }, 100);
  });
};

// 取消验证
const cancelVerify = () => {
  showVerify.value = false;
};

// 验证成功回调
const onVerifySuccess = () => {
  console.log('滑块验证成功');
  sheep.$helper.toast('验证通过');

  // 延迟执行登录过程，确保有足够时间完成验证动画
  setTimeout(() => {
    try {
      // 先隐藏验证码，避免组件被销毁后仍然尝试调用其方法
      showVerify.value = false;
      // 继续登录流程
      loginProcess();
    } catch (error) {
      console.error('验证成功后处理出错:', error);
      // 即使出错也继续登录流程
      loginProcess();
    }
  }, 800);
};

// 验证失败回调
const onVerifyFail = () => {
  console.log('滑块验证失败');
  sheep.$helper.toast('验证失败，请重试');
};

const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value;
};

// 登录处理流程
const loginProcess = () => {
  uni.showLoading({
    title: '登录中...',
    mask: true
  });

  sheep.$api.login.login(loginForm).then((loginRes) => {
    uni.hideLoading();
    // 处理登录成功逻辑
    if (loginRes.code == 200) {
      sheep.$store("user").userInfo = loginRes.userInfo;
      sheep.$store("user").isLogin = true;
      sheep.$helper.toast(loginRes.msg);
      console.log("用户信息:", loginRes);
      sheep.$router.go("/pages/index/index", {}, { reLaunch: true });
    } else {
      sheep.$helper.toast(loginRes.msg || "登录失败，请重试");
    }
  }).catch(error => {
    uni.hideLoading();
    sheep.$helper.toast("登录出错，请重试");
  });
};
</script>

<style lang="scss" scoped>
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.login-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f7fa;
}

.header-image-container {
  position: relative;
  height: 35vh;
  overflow: hidden;

  .header-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: linear-gradient(
      to top,
      #ffffff 0%,
      rgba(255, 255, 255, 0) 100%
    );
  }
}

.form-wrapper {
  flex: 1;
  padding: 80rpx 60rpx;
  border-top-left-radius: 80rpx;
  border-top-right-radius: 80rpx;
  margin-top: -150rpx;
  background-color: #ffffff;
  z-index: 10;
  
  display: flex;
  flex-direction: column;
  animation: fadeIn 0.8s ease-out forwards;
}

.title {
  font-size: 56rpx;
  color: #1e293b;
  font-weight: bold;
  margin-bottom: 20rpx;
  font-family: "AlimamaDongFangDaKai-Regular", "楷体", "KaiTi", serif;
}

.subtitle {
  font-size: 28rpx;
  color: #64748b;
  margin-bottom: 60rpx;
  margin-left: 20rpx;
  display: inline-block;
}

.input-container {
  display: flex;
  align-items: center;
  background-color: #f8fafc;
  border-radius: 20rpx;
  padding: 24rpx 30rpx;
  margin-bottom: 40rpx;
  transition: all 0.2s ease-in-out;
  border: 1px solid #e2e8f0;

  &:focus-within {
    background-color: #fff;
    border-color: #4f46e5;
  }

  .input-icon {
    width: 48rpx;
    height: 48rpx;
  }
}

.input-field {
  flex: 1;
  height: 100%;
  font-size: 32rpx;
  color: #1e293b;
  background: transparent;
  border: none;
  padding-left: 12px;

  &::placeholder {
    color: #94a3b8;
  }
}

.placeholder {
  color: #94a3b8;
}

.login-button {
  width: 100%;
  background: linear-gradient(to right, #4f46e5, #818cf8);
  color: #ffffff;
  font-weight: bold;
  border-radius: 20rpx;
  height: 100rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 50rpx;
  border: none;
  box-shadow: 0 8rpx 16rpx rgba(79, 70, 229, 0.2);
  transition: all 0.3s ease;

  &:active {
    transform: translateY(2px);
    background: linear-gradient(to right, #4338ca, #6366f1);
    box-shadow: 0 4rpx 8rpx rgba(79, 70, 229, 0.2);
  }
}

.login-button-text {
  font-size: 34rpx;
  letter-spacing: 2rpx;
}

.guest-button {
  width: 100%;
  background: linear-gradient(to right, #64748b, #94a3b8);
  color: #ffffff;
  font-weight: bold;
  border-radius: 20rpx;
  height: 100rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 30rpx;
  border: none;
  box-shadow: 0 8rpx 16rpx rgba(100, 116, 139, 0.2);
  transition: all 0.3s ease;

  &:active {
    transform: translateY(2px);
    background: linear-gradient(to right, #475569, #64748b);
    box-shadow: 0 4rpx 8rpx rgba(100, 116, 139, 0.2);
  }
}

.guest-button-text {
  font-size: 34rpx;
  letter-spacing: 2rpx;
}

.extra-links {
  display: flex;
  justify-content: space-between;
  margin-top: 40rpx;

  .link {
    font-size: 28rpx;
    color: #64748b;
    transition: color 0.2s;

    &:active {
      color: #1e293b;
    }
  }
}

/* 拼图验证样式 */
:deep(.fui-puzzle__verify-wrap) {
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
}

:deep(.fui-puzzle__slider-inner) {
  background: linear-gradient(to right, #2c5cdd, #7e3fe4);
}

:deep(.fui-puzzle__slider-btn) {
  background: #ffffff;
  box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.2);
}

.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx 0;
  background-color: transparent;
  display: flex;
  justify-content: center;
  z-index: 100;
  
  .copyright {
    font-size: 24rpx;
    color: #94a3b8;
    text-align: center;
  }
}
</style>
